package com.fyt.reachgo.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyt.reachgo.domain.Province;
import com.fyt.reachgo.domain.Result;
import com.fyt.reachgo.domain.VO.CityCallingCardVO;
import com.fyt.reachgo.service.ProvinceService;
import com.fyt.reachgo.mapper.ProvinceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.fyt.reachgo.utils.RedisConstants.CACHE_PROVINCE_KEY;
import static com.fyt.reachgo.utils.RedisConstants.CACHE_PROVINCE_TTL;

/**
* @author 27675
* @description 针对表【province(中国省份行政区划信息表)】的数据库操作Service实现
* @createDate 2025-02-25 08:41:39
*/
@Service
public class ProvinceServiceImpl extends ServiceImpl<ProvinceMapper, Province>
    implements ProvinceService{

    @Autowired
    private ProvinceMapper provinceMapper;

    private final StringRedisTemplate redisTemplate;

    public ProvinceServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Result<List<CityCallingCardVO>> getProvinceList() {
        // 1. 查询缓存（使用String类型存储）
        String cachedJson = redisTemplate.opsForValue().get(CACHE_PROVINCE_KEY);
        if (cachedJson != null && !cachedJson.isEmpty()) {// 如果缓存没有
            // 反序列化JSON字符串到对象列表
            List<CityCallingCardVO> provinceList = JSONUtil.toList(cachedJson, CityCallingCardVO.class);
            return Result.success(provinceList);
        }
        // 2. 缓存为空，查询数据库
        List<CityCallingCardVO> list = provinceMapper.getProvinceList();
        // 3. 序列化为JSON并存入缓存（使用String类型）
        String jsonStr = JSONUtil.toJsonStr(list);
        redisTemplate.opsForValue().set(CACHE_PROVINCE_KEY, jsonStr);
        redisTemplate.expire(CACHE_PROVINCE_KEY, CACHE_PROVINCE_TTL, TimeUnit.MINUTES);

        return Result.success(list);
    }
}



























